// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init();
const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const openid = cloud.getWXContext().OPENID
  var {userAddress} = event
  userAddress.openid=openid;
  //判断是否有重复地址
  var res=await db.collection("xiangcun_address").where(
    userAddress
  ).get()

   await db.collection("xiangcun_address").where({
    openid:openid
  }).update({
    data:{
      checked:false
    }
  })

  if (res.data.length){
  
   return await db.collection("xiangcun_address").where({
      _id:res.data[0]._id,
      openid:openid
    }).update({
      data:{
        checked:true
      }
    })
  }
  //没有重复地址
  userAddress.checked = true;
  return await db.collection("xiangcun_address").add({
    data: userAddress
  })
}